<%

/*
 * Copyright 2006 Brian Watkins
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

%>

<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="bw.news.*" %>
<%@ page import="bw.theme.*" %>
<%
    ThemeManager theme = ThemeManager.getInstance();
%>

<html>
<head>
<title>news!</title>
<!-- yahoo stuff -->
<script src="include/yahoo.js"></script>
<script src="include/dom.js"></script>
<script src="include/event.js"></script>
<script src="include/dragdrop.js"></script>
<script src="include/dragArrange.js"></script>
<script src="include/connection.js"></script>
<!-- end yahoo stuff -->
<script>
var button_lowColor = "<%= theme.getColor( "fgcolor" ) %>";
var button_medColor = "<%= theme.getColor( "buttonMed" ) %>";
var button_highColor = "<%= theme.getColor( "buttonHigh" ) %>";
var cat_bgcolor = "<%= theme.getColor( "bgcolor" ) %>";
var cat_medcolor = "<%= theme.getColor( "lightAccent" ) %>";
var cat_hicolor = "<%= theme.getColor( "fgcolor" ) %>";
</script>
<script src="include/buttons.js"></script>
<link rel=STYLESHEET type="text/css" href="style.jsp">
<link rel="SHORTCUT ICON" href="images/favicon.ico">
<script>

var currentFeed = '';
var currentSrcName = '';
var currentNSS = '';
var addCategoryLink = '';
var currentCatId = '';

function showAddCategory ()
{
  var t = document.createElement( "input" );
  t.setAttribute( "type", "text" );
  t.setAttribute( "name", "category" );
  t.setAttribute( "maxlength", "12" );
  t.setAttribute( "class", "categoryInput" );
  t.setAttribute( "onKeyPress", "addCategory(event,this)" );

  var c = document.getElementById( "addCategory" );
  addCategoryLink = c.firstChild;
  c.replaceChild( t, c.firstChild );

  var b = document.createElement( "div" );
  b.setAttribute( "class", "cancelNewsSource" );

  var cancelLink = document.createElement( "a" );
  cancelLink.setAttribute( "href", "javascript:cancelAddCategory()" );
  cancelLink.setAttribute( "class", "addNewsSourceLink" );
  cancelLink.appendChild( document.createTextNode( "Cancel" ) );

  b.appendChild( cancelLink );

  c.appendChild( b );

  t.focus();
}

function cancelAddCategory ()
{
  var c = document.getElementById( "addCategory" );
  while ( c.hasChildNodes() ) { c.removeChild( c.firstChild ); }
  c.appendChild( addCategoryLink );
}

function addCategory ( evt, f )
{
  if ( evt.which == 13 ) {
    //alert( "adding category: " + f.value );
    if ( f.value != '' ) {
      if ( catNameIsUnique( f.value ) ) {    
        requestNewCategory( f.value );
      }
      else {
        alert( "News category name must be unique!" );
      }
    }
    else {
      alert( "Enter a news category name!" );
    }
  }
}

function catNameIsUnique ( catName ) 
{
  var ncats = document.getElementById( "ncats" ).getElementsByTagName( "DIV" );
  for ( var i = 0; i < ncats.length; i++ ) {
    if ( ncats.item( i ).getAttribute( "newsCategoryName" ) != null &&
         ncats.item( i ).getAttribute( "newsCategoryName" ) == catName ) {
      return false;
    }
  }
  return true;
}

function requestNewCategory ( name )
{
  var surl = 'updateNews?action=createCat&name=' + escape( name );

  //alert( surl );

  var callback = 
  {
    success : handleNewCat,
    failure : handleNewCatFailure,
    argument : { catName : name }
  }

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function handleNewCat ( obj )
{
  var catId = new Number( obj.responseText );

  //alert( "creating category '" + obj.argument.catName + "' with id: '" + catId + "'" );

  createNewCat( catId, obj.argument.catName );

  //close the add category field
  cancelAddCategory();

  //highlight the new category
  showFeed( catId, obj.argument.catName );
}

function createNewCat ( catId, catName )
{
  var d = document.createElement( "DIV" );
  d.setAttribute( "id", "newsCategory_" + catId );
  d.setAttribute( "newsCategoryId", catId );
  d.setAttribute( "newsCategoryName", catName );
  d.setAttribute( "onClick", "showFeed( '" + catId + "', '" + catName + "' )" );
  d.setAttribute( "class", "newsSource" );
  d.setAttribute( "onMouseOver", "handleHighlight( this, '" + catName + "', 'over' )" );
  d.setAttribute( "onMouseOut", "handleHighlight( this, '" + catName + "', 'out' )" );

  var t = document.createElement( "TABLE" );
  t.setAttribute( "cellpadding", "0" );
  t.setAttribute( "cellspacing", "0" );
  t.setAttribute( "border", "0" );
  t.setAttribute( "width", "100%" );
  t.setAttribute( "style", "height:15px;" );
  var tr = document.createElement( "TR" );
  var tda = document.createElement( "TD" );
  tda.setAttribute( "valign", "top" );
  var sp = document.createElement( "SPAN" );
  sp.setAttribute( "class", "newsSourceText" );
  sp.appendChild( document.createTextNode( catName ) );
  tda.appendChild( sp );
  var tdb = document.createElement( "TD" );
  tdb.setAttribute( "align", "right" );
  var cvs = document.createElement( "CANVAS" );
  cvs.setAttribute( "id", "button.menuImg_" + catId );
  cvs.setAttribute( "width", "15" );
  cvs.setAttribute( "height", "15" );
  cvs.setAttribute( "onClick", "openCloseMenu( event, '" + catId + "' )" );
  cvs.setAttribute( "onMouseOver", "menuMouseOver( '" + catId + "' )" );
  cvs.setAttribute( "onMouseOut", "menuMouseOut( '" + catId + "' )" );
  tdb.appendChild( cvs );
  tr.appendChild( tda );
  tr.appendChild( tdb );
  t.appendChild( tr );

  var nsd = document.createElement( "DIV" );
  nsd.setAttribute( "id", "newsSelect_" + catId );
  nsd.setAttribute( "class", "nssHolderOff" );
  nsd.setAttribute( "onClick", "stopEvent(event);" );
  var f = document.createElement( "FORM" );
  f.setAttribute( "id", "newsSelectForm_" + catId );
  f.setAttribute( "action", "newsFeed.jsp" );
  f.setAttribute( "target", "newsFeedWindow" );
  var sel = document.createElement( "SELECT" );
  sel.setAttribute( "id", "catSelect_" + catId );
  sel.setAttribute( "name", "sourceId" );
  sel.setAttribute( "class", "newsSourceSelect" );
  sel.setAttribute( "onChange", "handleCatDropDown( this, '" + catId + "' )" );
  var opta = document.createElement( "OPTION" );
  opta.setAttribute( "value", "" );
  opta.innerHTML = 'New News';
  var optb = document.createElement( "OPTION" );
  optb.setAttribute( "value", "-1" );
  optb.innerHTML = 'Edit ...';
  var optc = document.createElement( "OPTION" );
  optc.setAttribute( "value", "-2" );
  optc.innerHTML = 'Add ...';
  sel.appendChild( opta );
  sel.appendChild( optb );
  sel.appendChild( optc );
  var hid = document.createElement( "INPUT" );
  hid.setAttribute( "type", "hidden" );
  hid.setAttribute( "name", "id" );
  hid.setAttribute( "value", catId );
  f.appendChild( sel );
  f.appendChild( hid );
  nsd.appendChild( f );

  d.appendChild( t );
  d.appendChild( nsd );

  var addCatDiv = document.getElementById( "addCategory" );
  var ncats = document.getElementById( "ncats" );
  ncats.insertBefore( d, addCatDiv );

  //make its draggable div
  var dd = document.createElement( "DIV" );
  dd.setAttribute( "id", "newsCatDrag_" + catId );
  dd.setAttribute( "class", "newsSourceDrag" );
  dd.innerHTML = "<table cellpadding='0' cellspacing='0' border='0' width='100%' height='100%'><tr><td valign='center' style='padding:0px 0px 1px 5px;' class='newsSourceText'>" + catName + "</td></tr></table>";

  var ndd = document.getElementById( "newsCatDrag_" + catId );
  if ( ndd != null ) {
    //if we find ndd this means that there is a draggable div with the
    //same id so go ahead and delete it. 
    document.body.removeChild( ndd );
  }

  document.body.insertBefore( dd, document.body.lastChild );

  //make it draggable
  DragApp.addCat( catId );
}

function handleNewCatFailure ( obj )
{
  alert( "Problem creating new news category!" );
}

function showFeed ( f, sourceName )
{
   clearBG( currentFeed, currentNSS, currentSrcName );

   //set it now because clearBG needs the last value
   currentCatId = f;

   var nsw = document.getElementById( 'newsCategory_' + f );
   nsw.className = 'nsSelected';
   nsw.style.background = cat_hicolor;

   var m = 'button.menuImg_' + f; 
   drawDown( m, false );

   document.getElementById( m ).style.cursor = 'pointer';

   var nfw = document.getElementById( "newsFeedWindow" );
   nfw.src = "newsFeed.jsp?id=" + f;    

   currentFeed = nsw;
   currentSrcName = sourceName;
}

function openCloseMenu ( evt, f )
{
  var nsw = document.getElementById( 'newsCategory_' + f );
  if ( currentFeed == nsw ) {
    var nss = document.getElementById( 'newsSelect_' + f );
    var m = 'button.menuImg_' + f; 
    if ( currentNSS == nss ) {
      nss.className = 'nssHolderOff';
      currentNSS = '';

      drawDown( m, true );

      eval( "dd_" + f + ".unlock();" );
    }
    else {
      nss.className = 'nssHolderOn';
      currentNSS = nss;

      drawUp( m, true );

      eval( "dd_" + f + ".lock();" );
    }

    stopEvent( evt );
  }
}

function menuMouseOver ( f )
{
  var nsw = document.getElementById( 'newsCategory_' + f );
  if ( currentFeed == nsw ) {
    var m = 'button.menuImg_' + f;
    if ( currentNSS == '' ) {
      drawDown( m, true );
    } else {
      drawUp( m, true );
    }
  }
}

function menuMouseOut ( f )
{
  var nsw = document.getElementById( 'newsCategory_' + f );
  if ( currentFeed == nsw ) {
    var m = 'button.menuImg_' + f;
    if ( currentNSS == '' ) {
      drawDown( m, false );
    } else {
      drawUp( m, false );
    }
  }
}

function handleCatDropDown ( w, catId )
{
  if ( w.options[ w.selectedIndex ].value == '-1' ) {
    //open the edit window
    var nfw = document.getElementById( "newsFeedWindow" );
    nfw.src = "editNewsCategory.jsp?catId=" + catId;    
  }
  else if ( w.options[ w.selectedIndex ].value == '-2' ) {
    //open the add window
    var nfw = document.getElementById( "newsFeedWindow" );
    nfw.src = "addNews.jsp?catId=" + catId;  
  }
  else {
    eval( "document.forms.newsSelectForm_" + catId + ".submit();" );
  }
}

function handleHighlight ( ns, name, state )
{
  if ( !dragging ) {
    if ( state == 'over' ) {
      if ( currentSrcName != name ) {
        ns.style.background = cat_medcolor;
      } else {
        ns.style.background = cat_hicolor;
      }
    } else if ( state == 'out' ) {
      if ( currentSrcName != name ) {
        ns.style.background = cat_bgcolor;
      } else {
        ns.style.background = cat_hicolor;
      }
    }
  }
}

</script>

</head>

<%

    String action = request.getParameter( "action" );

    NewsManager manager = NewsManager.getInstance();

%>

<body>

<div id="newsMain" class="mainNewsHolder">

<div id="ncats" class="newsCategories">
<% 

    int x = 0;
    Iterator cats = manager.getNewsCategories();
    while ( cats.hasNext() ) {
        NewsCategory cat = (NewsCategory) cats.next();
%>
    <div id="newsCategory_<%= cat.getId() %>" newsCategoryId="<%= cat.getId() %>" newsCategoryName="<%= cat.getName() %>" onClick="showFeed( '<%= cat.getId() %>', '<%= cat.getName() %>' )" class="newsSource" onMouseOver="handleHighlight( this, '<%= cat.getName() %>', 'over' )" onMouseOut="handleHighlight( this, '<%= cat.getName() %>', 'out' )">
    <table cellpadding="0" cellspacing="0" border="0" width="100%">
    <tr>
<%      int newItems = cat.getNewItemsCount(); %>
    <td><span class="newsSourceText"><%= cat.getName() %> <%= newItems > 0 ? "(" + String.valueOf( newItems ) + ")" : "" %></span></td>
    <td align="right"><canvas id="button.menuImg_<%= cat.getId() %>" width="15" height="15" onClick="openCloseMenu( event, '<%= cat.getId() %>' )" onMouseOver="menuMouseOver( '<%= cat.getId() %>' )" onMouseOut="menuMouseOut( '<%= cat.getId() %>' )"></canvas></td>
    </tr>
    </table>
      <div id="newsSelect_<%= cat.getId() %>" class="nssHolderOff" onClick="stopEvent(event);">
        <form id="newsSelectForm_<%= cat.getId() %>" action="newsFeed.jsp" target="newsFeedWindow">
        <select id="catSelect_<%= cat.getId() %>" name="sourceId" class="newsSourceSelect" onChange="handleCatDropDown( this, '<%= cat.getId() %>' )">
          <option value="">New News</option>
<% 
    Vector ns = cat.getNewsSources();
    for ( Enumeration e = ns.elements(); e.hasMoreElements(); ) {
      NewsSource s = (NewsSource) e.nextElement();
%>
          <option value="<%= s.getIdStr() %>"><%= s.getName() %></option>
<%
    }
%>
	  <option value="-1">Edit ...</option>
	  <option value="-2">Add ...</option>
        </select>
	<input type="hidden" name="id" value="<%= cat.getId() %>">
	</form>
      </div>
    </div>
<%
    }
%>
    <div id="addCategory" class="addNewsSource"><a href="javascript:showAddCategory()" class="addNewsSourceLink">Add Category</a></div>
</div>

<iframe id="newsFeedWindow" name="newsFeedWindow" class="newsFeed" frameborder="0" src="newsFeed.jsp">
You don't support iframes.
</iframe>

</div>

<div id="editPop" class="editNewsPop">
<iframe id="editWindow" class="editNewsWindow">
You don't support iframes, dude!
</iframe>
</div>

<jsp:include page="nav.html" />

</body>

<script>

function clearBG ( cfeed, cnss, cSourceName )
{
    if ( cfeed != '' )
    {
      cfeed.className = 'newsSource';
      cfeed.style.background = cat_bgcolor;      

      cfeed.getElementsByTagName( 'SELECT' ).item( 0 ).selectedIndex = 0;

      if ( cnss != '' ) 
      {
        cnss.className = 'nssHolderOff';
	currentNSS = '';
	eval( "dd_" + currentCatId + ".unlock();" );
      }

      if ( cSourceName != 'WW_NO_NAME' ) 
      {
        var newTextNode = document.createTextNode( cSourceName );

	var spans = cfeed.getElementsByTagName( 'SPAN' );
	var sp = spans.item( 0 );

        var oldTextNode = sp.childNodes.item( 0 );

        sp.removeChild( oldTextNode );
        sp.appendChild( newTextNode );
      }

      var cvs = cfeed.getElementsByTagName( 'CANVAS' );
      drawClear( cvs.item( 0 ).id );

      cvs.item( 0 ).style.cursor = 'default';
    }
}

function addNewsFeed ( catId, feed, feedId )
{
  var s = document.getElementById( "catSelect_" + catId );

  var o = document.createElement( "option" );
  o.text = feed;
  o.value = feedId;

  s.add( o, s.options[ s.length - 2 ] );      
}

function deleteNewsFeed ( catId, feedId )
{
  var s = document.getElementById( "catSelect_" + catId );
  var opts = s.options;
  for ( x = 0; x < opts.length; x++ ) {
    if ( feedId == opts[x].value ) {
      s.removeChild( opts[x] );
    }
  }
}

function editNewsFeed ( catId, feedName, feedId )
{
  var s = document.getElementById( "catSelect_" + catId );
  var opts = s.options;
  for ( x = 0; x < opts.length; x++ ) {
    if ( feedId == opts[x].value ) {
      opts[x].innerHTML = feedName;
    }
  }
}

function stopEvent ( evt )
{
  evt.stopPropagation();
}

DragApp = function () {
  return {
    init:function () {
<% Iterator cs = manager.getNewsCategories();
   while ( cs.hasNext() ) {
     NewsCategory cat = (NewsCategory) cs.next();
%>
      dd_<%= cat.getId() %> = new DragArrange( "newsCategory_<%= cat.getId() %>", 
                                               "newsCats" );
      dd_<%= cat.getId() %>.setDragElId( 'newsCatDrag_<%= cat.getId() %>' );
<% } %>
      var dd_add = new YAHOO.util.DDTarget( "addCategory", "newsCats" );
    }, 
    addCat:function( catId ) {
      eval( "dd_" + catId + " = new DragArrange( 'newsCategory_" + catId + "', 'newsCats' );" );
      eval( "dd_" + catId + ".setDragElId( 'newsCatDrag_" + catId + "' );" );
    }
  }
} (); 

YAHOO.util.Event.addListener(window, "load", doInit);    

function doInit ()
{
  DragApp.init();

  //show the first feed in the list
  var ncats = document.getElementById( "ncats" ).getElementsByTagName( "DIV" );
  var fcat = ncats.item( 0 );
  showFeed( fcat.getAttribute( "newsCategoryId" ), 
            fcat.getAttribute( "newsCategoryName" ) );
}

var dragging = false;

</script>

<%  Iterator cts = manager.getNewsCategories();
    while ( cts.hasNext() ) {
        NewsCategory cat = (NewsCategory) cts.next();
%>
<div id="newsCatDrag_<%= cat.getId() %>" class="newsSourceDrag">
<table cellpadding="0" cellspacing="0" border="0" width="100%" height="100%">
<tr><td valign="center" style="padding:0px 0px 1px 5px;">
<span class="newsSourceText"><%= cat.getName() %></span>
</td></tr></table>
</div>
<% } %>

</html>